package ac.neec.mio.ui.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import ac.neec.data.RecordDetail;
import ac.neec.data.SpecificActivities;
import ac.neec.db.service.SQLManager;
import ac.neec.listener.DialogFragmentCallback;
import ac.neec.mio.R;
import ac.neec.mio.record.list.DetailCallbackListener;
import ac.neec.mio.record.search.CallbackListener;
import ac.neec.mio.record.search.SearchCalenderDialog;
import ac.neec.mio.record.search.SearchSlidingDrawer;
import ac.neec.mio.ui.adapter.RecordDateAdapter;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.TextView;

public class RecordListFragment extends Fragment implements CallbackListener,
		OnItemClickListener, DetailCallbackListener, Serializable, DialogFragmentCallback<SpecificActivities> {

	public static final String START_CALENDER = "開始日";
	public static final String END_CALENDER = "終了日";
	public static final String BACK_STACK_RECORD_LIST = "RecordList ADD";

	private ImageButton startCalenderButton;
	private ImageButton endCalenderButton;
	private SearchSlidingDrawer searchSlidingDrawer;
	private SearchCalenderDialog startCalenderDialog;
	private SearchCalenderDialog endCalenderDialog;
	private TextView startDate;
	private TextView endDate;
	private RecordDateAdapter adapter;
	private ListView listView;
	private Context activity;
	private ImageButton handle;
	private Button selectButton;
	private Button resetButton;
	private Button dateResetButton;
	private TextView typeText;
	private View view;
	private static boolean fragmentShowFrag;
	private FragmentManager fragmentManager;
	private RecordDetailFragment fragment;
	private String startDateData;
	private String endDateData;
	private String typeData;
	private String detailData;
	private List<RecordDetail> searchResultList = new ArrayList<RecordDetail>();
	private List<RecordDetail> bank = new ArrayList<RecordDetail>();

	public RecordListFragment() {
	}

	public static void setShowFlag(boolean flag) {
		fragmentShowFrag = flag;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_record_list, container, false);
		fragmentManager = getFragmentManager();
		initFindViews();
		setLintener();
		setRecordList();
		setDataBank();
		fragmentShowFrag = false;
		return view;
	}

	private void setDataBank() {
		bank.clear();
		bank.addAll(SQLManager.selectRecordDetailAll());
	}

	private void setRecordList() {
		List<RecordDetail> list = SQLManager.selectRecordDetailAll();
		Collections.reverse(list);
		adapter = new RecordDateAdapter(activity, R.layout.activity_record,list);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
	}

	private void setSearchResultRecordList() {

		if (searchResultList.isEmpty()) {
			new SearchErrorDialog().show(getFragmentManager(), "");
			return;
		}
		adapter = new RecordDateAdapter(activity, R.layout.activity_record, searchResultList);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
	}

	private void initFindViews() {
		searchSlidingDrawer = (SearchSlidingDrawer) view.findViewById(R.id.drawer);
		startCalenderButton = (ImageButton) view.findViewById(R.id.btn_start_calender);
		endCalenderButton = (ImageButton) view.findViewById(R.id.btn_end_calender);
		startDate = (TextView) view.findViewById(R.id.text_start_date);
		endDate = (TextView) view.findViewById(R.id.text_end_date);
		searchSlidingDrawer.setDateText(startDate, endDate);
		listView = (ListView) view.findViewById(R.id.list_record);
		handle = (ImageButton) view.findViewById(R.id.handle);
		selectButton = (Button) view.findViewById(R.id.btn_type_select);
		typeText = (TextView) view.findViewById(R.id.text_type);
		selectButton = (Button) view.findViewById(R.id.btn_type_select);
		resetButton = (Button) view.findViewById(R.id.btn_reset);
		dateResetButton = (Button)view.findViewById(R.id.btn_date_reset);
	}

	@SuppressWarnings("deprecation")
	private void setLintener() {
		startCalenderButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				startCalenderDialog = createDialog(SearchCalenderDialog.START_DATE_SETTING);
				startCalenderDialog.show(getFragmentManager(), START_CALENDER);
			}
		});
		endCalenderButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				endCalenderDialog = createDialog(SearchCalenderDialog.END_DATE_SETTING);
				endCalenderDialog.show(getFragmentManager(), END_CALENDER);
			}
		});
		selectButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showTypeSelect();
			}
		});
		resetButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				typeText.setText("");
			}
		});
		dateResetButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				startDate.setText(SearchSlidingDrawer.getDateToday());
				endDate.setText(SearchSlidingDrawer.getDateToday());

			}
		});

		searchSlidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			@Override
			public void onDrawerOpened() {
				fragmentShowFrag = true;
			}
		});
		searchSlidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			@Override
			public void onDrawerClosed() {
				fragmentShowFrag = false;
				adapter.clear();
				setInputData();
				setSearchResultData();
				setSearchResultRecordList();
			}
		});
	}

	private void setInputData() {
		startDateData = String.valueOf(startDate.getText());
		endDateData = String.valueOf(endDate.getText());
		typeData = String.valueOf(typeText.getText());
	}

	private void setSearchResultData() {
		List<RecordDetail> list = new ArrayList<RecordDetail>();
		String inputStartDate = String.valueOf(startDate.getText());
		String inputEndDate = String.valueOf(endDate.getText());

		for (RecordDetail data : bank) {
			if (inputStartDate.equals(data.getRecordDate().getDate())
					|| inputEndDate.equals(data.getRecordDate().getDate())) {
				list.add(data);
			} else if (inputStartDate.compareTo(data.getRecordDate().getDate()) < 0
					&& inputEndDate.compareTo(data.getRecordDate().getDate()) > 0) {
				list.add(data);
			}
		}
		if (typeText.getText().length() == 0) {
			searchResultList.addAll(list);
			return;
		}
		for (RecordDetail data : list) {
			if (typeText.getText().equals(data.getActivities().getMajorHeadingTitleJP())) {
				searchResultList.add(data);
			}
		}
	}

	private void showTypeSelect() {
		new SelectListDialogFragment((CallbackListener) this).show(fragmentManager, detailData);
	}

	private SearchCalenderDialog createDialog(int condition) {
		return new SearchCalenderDialog(
				condition, this,
				searchSlidingDrawer.getnYear(), searchSlidingDrawer.getnMonth(),
				searchSlidingDrawer.getnDay());
	}

	private void showDetailFragment(int item, RecordDetail detail, boolean addStack) {
		fragment = new RecordDetailFragment();
		fragment.setItem(detail, item, adapter.getSize());
		fragment.setCallbackListener(this);
		FragmentTransaction transaction = getFragmentManager().beginTransaction();
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.popBackStack();
		transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		transaction.replace(R.id.fragment_record_list_container, fragment);
		transaction.addToBackStack(BACK_STACK_RECORD_LIST);
		transaction.commit();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (!fragmentShowFrag) {
			ListView list = (ListView) arg0;
			RecordDetail item = (RecordDetail) list.getItemAtPosition(arg2);
			showDetailFragment(arg2, item, true);
			fragmentShowFrag = true;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		adapter.clear();
	}

	@Override
	public void startDateUpdate(int y, int m, int d) {
		searchSlidingDrawer.setStartDate(y, m, d);
	}

	@Override
	public void endDateUpdate(int y, int m, int d) {
		searchSlidingDrawer.setEndDate(y, m, d);
	}

	public void moveLeftDetail() {
		if (adapter.getItem() > 0) {
			showDetailFragment(adapter.getItem() - 1, (RecordDetail) listView.getItemAtPosition(adapter.getItem() - 1),
					false);
			adapter.setItem(adapter.getItem() - 1);
		}
	}

	public void moveRightDetail() {
		if (adapter.getSize() - 1 >= adapter.getItem()) {
			showDetailFragment(adapter.getItem() + 1, (RecordDetail) listView.getItemAtPosition(adapter.getItem() + 1),
					false);
			adapter.setItem(adapter.getItem() + 1);
		}
	}

	@Override
	public void showBackDetail(int item) {
		if (item > 0)
			showDetailFragment(item - 1, (RecordDetail) listView.getItemAtPosition(adapter.getItem() - 1), false);
	}

	@Override
	public void showNextDetail(int item) {
		if (adapter.getSize() - 1 >= item)
			showDetailFragment(item + 1, (RecordDetail) listView.getItemAtPosition(adapter.getItem() + 1), false);
	}

	@Override
	public void callbackData(SpecificActivities value) {

	}

	@Override
	public void select(String text) {
		typeText.setText(text);
	}
}
